package com.example.personalcenter.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.personalcenter.InterestActivity;
import com.example.personalcenter.LoginActivity;
import com.example.personalcenter.databinding.FragmentProfileBinding;
import com.example.personalcenter.model.UserViewModel;
import com.example.personalcenter.util.SharedPrefUtil;

public class ProfileFragment extends Fragment {

    private FragmentProfileBinding binding;
    private UserViewModel userVM;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FragmentProfileBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view,
                              @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        userVM = new ViewModelProvider(requireActivity()).get(UserViewModel.class);

        String email = SharedPrefUtil.getEmail(requireContext());
        binding.tvEmail.setText("邮箱：" + email);

        userVM.getInterest().observe(getViewLifecycleOwner(),
                interest -> binding.tvInterest.setText("当前兴趣：" + interest));

        binding.btnSelectInterest.setOnClickListener(v -> {
            Intent intent = new Intent(requireContext(), InterestActivity.class);
            startActivityForResult(intent, 1001);
        });

        binding.btnLogout.setOnClickListener(v -> {
            SharedPrefUtil.clear(requireContext());
            startActivity(new Intent(requireContext(), LoginActivity.class));
            requireActivity().finish();
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == android.app.Activity.RESULT_OK) {
            // 选择兴趣后，立刻通知首页
            String newInterest = SharedPrefUtil.getInterest(requireContext());
            userVM.setInterest(newInterest); // ← 这里立刻通知首页
        }
    }
}